import toast from '@vant/weapp/toast/toast'
import http from "../../utils/request"
Page({
  data: {
    encryptedData:"",
    iv:"",
    show: false,
    userInfo:{
      nickname:"未登录",
      avatarurl:"/static/img/user.jpg",
      profile:"请登录以使用更多功能"
    }
  },
  onLoad(){
  },
  onShow(){
  },
  login(){
    wx.getUserProfile({
      desc: '获取您的信息用于注册登录',
      success:(res)=>{
        console.log(res)
        this.setData({
          encryptedData:res.encryptedData,
          iv:res.iv
        })
        toast.loading({
          message: '登录中',
          forbidClick: true,
          duration:5000,
          onClose:()=>{
            toast.fail({
              message:"请求超时"
            })
          }
        });
        wx.login({
          timeout:5000,
          success: (res) => {
            if(res.code){
              wx.request({
                url: 'http://localhost:8080/user/login',
                method:'POST',
                header:{
                  'content-type':'application/x-www-form-urlencoded'
                },
                data:{
                  code:res.code,
                  encryptedData:this.data.encryptedData,
                  iv:this.data.iv
                },
                success:(res)=>{
                  toast.success({
                    message:"登录成功",
                    duration:1500
                  })
                  wx.setStorage({
                    key:"token",
                    data:res.data.data.token
                  })
                  wx.setStorage({
                    key:"expire",
                    data:Date.parse(new Date())+1000*60*60*24
                  })
                  this.setData({
                    userInfo:{
                      nickname:res.data.data.userInfo.nickname,
                      avatarurl:res.data.data.userInfo.avatarurl,
                      profile:res.data.data.userInfo.profile
                    }
                  })       
                }
              })
            }
          },
          fail:(res)=>{
            console.log("error",res)
            toast.fail({
              message:"登录失败",
              duration:1500
            })
          }
        })
      }
    })
  console.log(wx.getStorageSync('token'))
  },
})